import { NInput } from 'naive-ui'
import { defineComponent, nextTick, ref, h } from 'vue'

const ShowOrEdit = defineComponent({
  props: {
    value: [String, Number],
    onUpdateValue: [Function, Array]
  },
  setup(props) {
    const isEdit = ref(false)
    const inputRef = ref(null)
    const inputValue = ref(props.value)
    function handleOnClick() {
      isEdit.value = true
      nextTick(() => {
        inputRef.value.focus()
      })
    }
    function handleChange() {
      props.onUpdateValue(inputValue.value)
      isEdit.value = false
    }
    return () =>
      h(
        'div',
        {
          onClick: handleOnClick,
          style: 'min-width:30px;height:23px'
        },
        isEdit.value
          ? h(
              NInput,
              {
                ref: inputRef,
                value: inputValue.value,
                size: 'tiny',
                onUpdateValue: (v) => {
                  inputValue.value = v
                },
                onChange: handleChange,
                onBlur: handleChange
              },
              null
            )
          : props.value
      )
  }
})

export default ShowOrEdit
